package cn.org.guhao.practice.go.service;

import cn.org.guhao.practice.go.dao.DepartmentDao;
import cn.org.guhao.practice.go.model.Department;
import cn.org.guhao.practice.go.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class DepartmentService {

  private static final Logger logger = LoggerFactory.getLogger(DepartmentService.class);

  private DepartmentDao departmentDao;

  public List<Department> getDepartments(){
    List<Department> departments = departmentDao.findAll();
    for(Department department:departments){
      findSub(department,departments);
    }
    return departments;
  }

  public List<Department> findRootDepartments(List<Department> departments){
    List<Department> rootDepartments = new ArrayList<Department>();
    Iterator<Department> it = departments.iterator();
    while (it.hasNext()){
      Department department = it.next();
      if(department.getParentId() == null){
        rootDepartments.add(department);
        it.remove();
      }
    }
    return rootDepartments;
  }

  public List<Department> buildRef(List<Department> departments){
    List<Department> rootDepartments = findRootDepartments(departments);
    return buildRef(rootDepartments,departments);
  }

  public List<Department> buildRef(List<Department> rootDepartments,List<Department> departments){
    for(Department rootDepartment:rootDepartments){
      findSub(rootDepartment,departments);
    }
    return rootDepartments;
  }

  public void findSub(Department parentDepartment,List<Department> departments){
    Iterator<Department> it = departments.iterator();
    while (it.hasNext()){
      Department sd = it.next();
      if(parentDepartment.getId().equals(sd.getParentId())){
        parentDepartment.add(sd);
//        it.remove();
        findSub(sd,departments);
      }
    }
  }

  public void printRef(List<Department> departments,int level){
    for (Department department:departments){
      StringBuilder info = new StringBuilder();
      for (int i=0;i<level;i++){
        info.append("-");
      }
      info.append(StringUtils.BLANK).append(department.getName());
      logger.info(info.toString());
      if(department.getSubDepartments() != null && department.getSubDepartments().size()>0) {
        printRef(department.getSubDepartments(), level + 1);
      }
    }
  }

}
